package com.qk.exception;

import com.qk.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("程序运行错误: ", e);
        return Result.error("对不去,网络波动,请稍后再试!!!");
    }


    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        String message = e.getMessage();
        if (message.contains("Duplicate entry")){
            String msg = message.substring(message.indexOf("Duplicate entry"));
            String[] arr = msg.split(" ");
            return Result.error("数据已存在:" + arr[2]);
        }
        return Result.error("对不去,网络波动,请稍后再试!!!");
    }

    @ExceptionHandler
    public Result handleBusinessException(BusinessException e) {
        log.error("程序运行错误: ", e);
        return Result.error(e.getMessage());
    }

}
